<?php

namespace App\Http\Controllers\System;

use App\Http\Controllers\Controller;
use App\Models\System\SystemConfig;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class SystemConfigController extends Controller
{
    protected Request $request;
    protected Model $model;

    public function __construct(Request $request,SystemConfig $systemConfig)
    {
        $this->request=$request;
        $this->model = $systemConfig;
    }

    /**
     * Display a listing of the resource.
     */
    public function index():JsonResponse
    {
        $perPage=$this->request->per_page??10;
        $list=$this->model->modelSearch($this->request,$this->model)
            ->orderByDesc('id')
            ->paginate($perPage);
        $this->saveOperationLog('查询系统配置列表');
        return $this->success($list);
    }
    //
    public function setConfig(){
        if(!$this->request->filled('key') || !$this->request->filled('value')){
            return $this->fail('key和value不能为空');
        }
        $condition=[
            'key'=>$this->request->key,
        ];
        $data=[
            'type'=>$this->request->type,
            'value'=>$this->request->value,
        ];
        SystemConfig::updateOrCreate($condition,$data);
        $this->saveOperationLog('添加修改系统配置');
        return $this->successMsg();
    }
    //
    public function getConfigByKey(){
        if(!$this->request->filled('key')){
            return $this->fail('key不能为空');
        }
        $data=SystemConfig::where('key',$this->request->key)->first();
        $this->saveOperationLog('获取系统配置by key');
        return $this->success($data);
    }
    //
    public function getConfigByType(){
        if(!$this->request->filled('type')){
            return $this->fail('type不能为空');
        }
        $data=SystemConfig::where('type',$this->request->type)->get();
        $this->saveOperationLog('获取系统配置by type');
        return $this->success($data);
    }
    //
    public function destroyConfig(){
        if(!$this->request->filled('key')){
            return $this->fail('key不能为空');
        }
        SystemConfig::where('key',$this->request->key)->delete();
        $this->saveOperationLog('删除系统配置');
        return $this->successMsg();
    }


}
